package com.wits.qso.service;

import java.text.NumberFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authc.credential.PasswordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import com.wits.platform.common.constants.UserType;
import com.wits.platform.dao.MmrUserRoleDao;
import com.wits.platform.entity.MmrUserRole;
import com.wits.platform.entity.MmrUserRolePK;
import com.wits.platform.entity.User;
import com.wits.platform.service.BaseService;
import com.wits.platform.service.UserService;
import com.wits.qso.dao.TeacherDao;
import com.wits.qso.entity.Teacher;
import com.wits.qso.util.UserRoleType;


@Component
public class TeacherService extends BaseService<Teacher, String>
{

	protected static final Logger logger = LoggerFactory.getLogger( TeacherService.class );
	private TeacherDao teacherDao;
	@Autowired
	private UserService userService = null;
	@Autowired
	private PasswordService passwordService = null;
	@Resource
	private MmrUserRoleDao mmrUserRoleDao;

	@Autowired
	public void setTeacherDao(TeacherDao teacherDao) {
		this.baseDao = teacherDao;
		this.teacherDao = teacherDao;
	}

	public User getUser(String id) {
		List<User> list = teacherDao.getUser( id );
		if (list.size() > 0)
			return list.get( 0 );
		else
			return null;
	}

	/**
	 * @see 根据userId查询
	 * @param userId
	 * @return
	 */
	public Teacher findByUserId(final String userId) {
		return teacherDao.findOne( new Specification<Teacher>() {
			@Override
			public Predicate toPredicate(Root<Teacher> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				return cb.equal( root.get( "terUserId" ), userId );
			}
		} );
	}
	
	public void insertUserRole(MmrUserRole model){
		mmrUserRoleDao.save(model);
	}
	
	public void deleteUserRole(String userId){
		mmrUserRoleDao.deleteByUserId(userId);
	}
	
	public int batchTeacherData(Workbook workbook, String currentUserId) {
		int result = 0;
		Sheet sheet = workbook.getSheetAt( 0 );
		try {
			for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
				Row row = sheet.getRow( i );
				Teacher teacher = new Teacher();
				teacher.setTerName( (String) getCellValue( row.getCell( 0 ) ) );
				teacher.setTerSex( (String) getCellValue( row.getCell( 1 ) ) );
				teacher.setTerTel( (String) getCellValue( row.getCell( 2 ) ) );
				teacher.setTerMail( (String) getCellValue( row.getCell( 3 ) ) );
				teacher.setTerUserId( (String) getCellValue( row.getCell( 4 ) ) );
				teacher.setDateExpire( (Date) getCellValue( row.getCell( 5 ) ) );
				teacher.setRemark( (String) getCellValue( row.getCell( 6 ) ) );
				teacher.setDateCre( new Date() );
				teacher.setUserCre( currentUserId );

				User user = new User();
				user.setUserId( teacher.getTerUserId() );
				user.setUserNameC( teacher.getTerName() );
				user.setDateExpire( teacher.getDateExpire() );
				user.setIsEnable( "T" );
				user.setUsertype( UserType.TEACHER.getValue() );
				user.setUserPassword( passwordService.encryptPassword( "123456" ) );
				user.setUserCre( currentUserId );
				user.setUserEmail( teacher.getTerMail() );
				user.setDateCre( new Date() );

				if (!userService.isExist( user )) {
					this.save( teacher );
					userService.saveCascade( user ); // 保存到wits_user表
					insertUserRole(new MmrUserRole(new MmrUserRolePK(user.getUserId(), UserRoleType.TeacerRole.getValue())));
					result++;
				}
			}
		} catch (Throwable cause) {
			logger.error( cause.getMessage(), cause );
		}

		return result;
	}

	private Object getCellValue(Cell cell) {
		Object result = null;
		if (null != cell) {
			switch (cell.getCellType()) {
			case Cell.CELL_TYPE_STRING:
				result = cell.getRichStringCellValue().getString();
				break;
			case Cell.CELL_TYPE_NUMERIC:
				if (DateUtil.isCellDateFormatted( cell )) {
					result = cell.getDateCellValue();
				} else {
					NumberFormat nf = NumberFormat.getInstance();
					nf.setGroupingUsed( false );
					result = String.valueOf( nf.format( cell.getNumericCellValue() ) );
				}
				break;
			}
		}

		return result;
	}
}
